package benworks.java.util.concurrent.fork;

import java.util.concurrent.ExecutionException;
import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.Future;
import java.util.concurrent.RecursiveTask;

/**
 * Fork/Join设计初衷针对单机多核（处理器数量很多的情况）。<br>
 * Fork/Join可以是较小粒度的切分，任务自己知道该如何切分自己，递归地切分到一组合适大小的子任务来执行，<br>
 * 因为是同一个JVM内，所以彼此间通信是很容易的，更像是传统编程方式。<br>
 * 
 * @author Administrator
 *
 */
public class CounterTask extends RecursiveTask<Integer> {
	private static final long serialVersionUID = -4970793927082010144L;
	private static final int THRESHOLD = 2;
	private int start;
	private int end;

	public CounterTask(int start, int end) {
		this.start = start;
		this.end = end;
	}

	@Override
	protected Integer compute() {
		int sum = 0;
		boolean canComputer = (end - start) <= THRESHOLD;
		if (canComputer) {
			for (int i = start; i <= end; i++) {
				sum += i;
			}
		} else {
			int middle = (start + end) / 2;
			CounterTask leftTask = new CounterTask(start, middle);
			CounterTask rightTask = new CounterTask(middle + 1, end);
			leftTask.fork();
			rightTask.fork();
			int leftResult = leftTask.join();
			int rightResult = rightTask.join();
			sum = leftResult + rightResult;
		}
		return sum;
	}

	public static void main(String[] args) {
		ForkJoinPool pool = new ForkJoinPool();
		CounterTask task = new CounterTask(1, 4);
		Future<Integer> result = pool.submit(task);
		try {
			System.out.println("result is:" + result.get());
		} catch (InterruptedException e) {
		} catch (ExecutionException e) {
		} finally {
			pool.shutdown();
		}
	}

}